#include "Config.h"
#include "TitleScreen.h"
#include <iostream>

TitleScreen::TitleScreen(Engine *engine)
  : fEngine(engine),
    fFont(0)
{
  fFont = TTF_OpenFont("FreeSans.ttf", 24);
}

TitleScreen::~TitleScreen()
{
  if(fFont)
    TTF_CloseFont(fFont);
  fFont = 0;
}

int
TitleScreen::Run()
{
  SDL_Color white = { 255, 255, 255};
  SDL_Surface *temp;
  SDL_Rect rect = { 0, 0, 0, 0 };

  fScreen = fEngine->GetSurface();
  temp = IMG_Load("gfx/title.png");
  SDL_BlitSurface(temp, 0, fScreen, &rect);
  delete temp;

  rect.x = 300;
  rect.y = 300;
  temp = TTF_RenderUTF8_Blended(fFont, "(1) New game", white);
  SDL_BlitSurface(temp, 0, fScreen, &rect);
  delete temp;

  rect.y = 330;
  temp = TTF_RenderUTF8_Blended(fFont, "(2) Enter code", white);
  SDL_BlitSurface(temp, 0, fScreen, &rect);
  delete temp;

  rect.y = 360;
  temp = TTF_RenderUTF8_Blended(fFont, "(3) Quit", white);
  SDL_BlitSurface(temp, 0, fScreen, &rect);
  delete temp;

  SDL_Flip(fScreen);
  SDL_Event event;
  SDLKey key;
  bool done = false;
  int ret = E_DONE;
  while (!done)
  {
    if (SDL_WaitEvent(NULL)) {
      while (SDL_PollEvent(&event)) {
        switch (event.type) {
          case SDL_KEYUP:
            key = event.key.keysym.sym;
            if (key == SDLK_ESCAPE || key == SDLK_3) {
              done = true;
              ret = E_DONE;
            }
            else if (key == SDLK_1) {
              done = true;
              ret = E_OK;
            }
            break;
          case SDL_QUIT:
            ret = E_DONE;
            done = true;
            break;
        }
      }
    }
  }
  return ret;
}

